import cv2
import requests
import threading
import socket
import select
import time

# 服务器URL
lunch_code = '1631'
id = str(0)
video_server_url = f'http://127.0.0.1:80/get_video/{lunch_code}{id}'
data_server_url = f'http://127.0.0.1:80/get_data_rst/{lunch_code}{id}'
comd_server_url = f'http://127.0.0.1:80/upload_comd/{lunch_code}{id}'

# 本地TCP端口
def tcp_server_init():
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.bind(('127.0.0.1', 8888))
    tcp_server_socket.listen(1)
    return tcp_server_socket

def video_thread_function():
    video_response = cv2.VideoCapture(video_server_url)
    while True:
        ret, frame = video_response.read()
        if not ret:
            print("Failed to receive video frame")
            break
        cv2.imshow('Video', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()

def combined_listener_sender():
    tcp_server_socket = tcp_server_init()
    while True:
        print("Waiting for TCP connection...")
        conn, addr = tcp_server_socket.accept()  # 接受TCP连接
        print(f"Connected to {addr}")
        try:
            global msg_huan, launch
            launch = True
            msg_huan = b""
            def send_all():
                global msg_huan
                if msg_huan:
                    conn.sendall(msg_huan)  # 发送到TCP连接
                    print(f"Received data: {msg_huan}")
                    msg_huan = b""
                    return True
                else:
                    return False
            def recv_all():
                global msg_huan, launch
                while launch:
                    # 读取服务器的数据
                    try:
                        response = requests.get(data_server_url)
                        if response.status_code == 200:
                            data = response.json()
                            hex_data = ""
                            for i in data:
                                hex_data = hex_data + i[1]
                            # 将16进制字符串转换回字节数据
                            byte_data = bytes.fromhex(hex_data)
                            msg_huan = msg_huan + byte_data
                    except requests.RequestException as e:
                        print(f"Failed to get data: {e}")
                        break
                    time.sleep(0.01)  # 添加延迟，确保请求频率不会太快
            # 启动线程监听服务器数据
            recv_thread = threading.Thread(target=recv_all)
            recv_thread.start()
            while True:
                try:
                    # 处理TCP接收
                    send_all()
                    data = conn.recv(1024)
                    send_all()
                    if data:
                        hex_data = data.hex()
                        print(f"Received comd data: {data}")
                        response = requests.post(comd_server_url, data={'comd_data': hex_data})
                        if response.status_code != 200:
                            print(f"Failed to upload comd data: {response.json()}")
                    time.sleep(0.5)  # 添加延迟，确保请求频率不会太快
                    send_all()
                    
                except:
                    print("Connection reset by peer")
                    launch = False  #结束线程
                    break
        except:
            print("Connection reset by peer")

# 创建线程
video_thread = threading.Thread(target=video_thread_function)
#combined_thread = threading.Thread(target=combined_listener_sender)

# 启动线程
if __name__ == '__main__':
    video_thread.start()
    #combined_thread.start()
    combined_listener_sender()
